<?php

namespace App\Dao;

use App\Exceptions\SysExceptions;
use App\Model\OrdersModel;
use Illuminate\Support\Facades\DB;

class OrdersDao extends BaseDao
{
    public static function builder_query($params = []): \Illuminate\Database\Eloquent\Builder
    {
        $query = OrdersModel::query();
        $query->when(checkIsHasField($params,'orders_id'),function ($query)use ($params){
            $query->where('orders_id',$params['orders_id']);
        });

        $query->when(checkIsHasField($params,'orders_code'),function ($query)use ($params){
            $query->where('orders_code',$params['orders_code']);
        });

        $query->when(checkIsHasField($params,'status'),function ($query)use ($params){
            $query->where('status',$params['status']);
        });

        $query->when(checkIsHasField($params,'user_id'),function ($query)use ($params){
            $query->where('user_id',$params['user_id']);
        });
        return $query->orderByDesc('created_at');
    }
    public static function orders($params = []): \Illuminate\Contracts\Pagination\LengthAwarePaginator
    {
        return self::builder_query($params)->paginate();
    }

    public static function orders_info($params = []): array
    {
        return self::builder_query($params)->first()->toArray();
    }


    /**
     * @desc 订单下单
     * @param array $params
     * @return void
     * @throws SysExceptions
     */
    public static function orders_create(array $params = [])
    {
        checkForData(['user_id','goods_id','address_id','pay_pass'],['用户不正确','请选择商品','请选择地址','请输入支付密码'],$params);
        //检测用户支付密码
        UsersDao::check_pass($params['pay_pass'],$params['user_id']);
        $address_query = AddressDao::get_address_builder_query(['address_id'=>$params['address_id']]);
        if(!$address_query->exists()){
            self::error('地址不存在');
        }
        $address_info = $address_query->first()->toArray();
        $goods_query = GoodsDao::builder_query(['goods_id'=>$params['goods_id'],'show'=>1]);
        if(!$goods_query->exists()){
            self::error('请选择正确的商品');
        }
        //商品信息
        $goods_info = $goods_query->first()->toArray();
        //获取用户信息
        $user_query = UsersDao::builder_query(['user_id'=>$params['user_id']]);
        if(!$user_query->exists()){
            self::error('用户不存在');
        }
        //用户信息
        $user_info = $user_query->first()->toArray();
        if($user_info['money'] < $goods_info['goods_price']){
            self::error('金额不足!');
        }
        //创建订单
        $order_data = [
            'user_id'=>$params['user_id'],
            'status'=>1,
            'price'=>$goods_info['goods_price'],
            'orders_code'=>makeOrderNo(),
            'goods_id'=>$params['goods_id'],
            'address_id'=>$params['address_id'],
            'address_json'=>json_encode($address_info,JSON_UNESCAPED_UNICODE),
            'orders_json_data'=>json_encode($goods_info,JSON_UNESCAPED_UNICODE),
        ];
        //如果有店铺号码
        if(checkIsHasField($params,'shop_nums')){
            $order_data['shop_nums'] = $params['shop_nums'];
        }
        //创建订单并且扣费
        DB::beginTransaction();
        try {
            self::builder_query()->create($order_data);
            BillsDao::moneysUpdate(-($order_data['price']),$order_data['user_id'],'购买商品扣费');
            DB::commit();
        }catch (\Exception $exception){
            DB::rollBack();
            self::error($exception->getMessage());
        }
    }

    /**
     * @throws SysExceptions
     */
    public static function userUploadInfo(array $params)
    {
        //查询状态已经发货不允许修改
        checkForData(['orders_id','user_uplaod_info'],['请选择订单','请填写上传信息'],$params);
        $order_query = self::builder_query(['orders_id'=>$params['orders_id']]);
        if(!$order_query->exists()){
            self::error('订单不存在');
        }
        $orders_info = $order_query->first()->toArray();
        if($orders_info['status'] > 2){
            self::error('订单状态不正确!');
        }
        if(!$order_query->update([
            'user_uplaod_info' => json_encode($params['user_uplaod_info'], JSON_UNESCAPED_UNICODE),
            'status'=>2
        ])){
            self::error('订单修改失败!');
        }
    }

    /**
     * @desc 订单发货
     * @param array|null $params
     * @return void
     * @throws SysExceptions
     */
    public static function send_orders(array $params)
    {
        checkForData(['wuliu_num'],['请输入物流单号'],$params);
        $orders_query = self::builder_query(['orders_id'=>$params['orders_id']]);
        if(!$orders_query->exists()){
            self::error('订单不存在!');
        }
        $orders_info = $orders_query->first()->toArray();
        if($orders_info['status'] != 1){
            self::error('订单状态不正确!');
        }

        if (self::builder_query(['orders_id'=>self::deleteParamId($params,'orders_id')])->update(['wuliu_num'=>$params['wuliu_num'],'status'=>3]) === false){
            self::error('修改失败');
        }
    }

    public static function confirm(array $params)
    {
        //确认收货升级/返佣
        $orderQuery = self::builder_query([
            'orders_code'=>$params['orders_code']
        ]);
        //订单不存在
        if(!$orderQuery->exists()){
            self::error('订单不存在!');
        }
        //订单信息
        $orderInfo = $orderQuery->first()->toArray();

        if($orderInfo['status'] != 3){
            self::error('状态不正确');
        }
        //确认收货并且绑定
        DB::beginTransaction();
        try {
            //确认收货
            $orderQuery->update([
                'status'=>4
            ]);
            //返费10%给第三节点的上级

            self::changeLevel($orderInfo);
            self::changeData($orderInfo);
            self::changeShopData($orderInfo);
            //进行升级或者返费
            DB::commit();
        }catch (\Exception $exception){
            DB::rollBack();
            var_dump($exception->getMessage());
        }
    }

    /**
     * @desc 返费接口
     * @param array $orderInfo
     * @return void
     * @throws SysExceptions
     */
    private static function changeData(array $orderInfo)
    {
        //获取PV
        $goodsInfo = json_decode($orderInfo['orders_json_data'],true);
        $pv = $goodsInfo['pv'];
        //没有PV不参加
        if($pv == 0){
            return;
        }
        //判断上级
        $userInfo = UsersDao::builder_query(['user_id'=>$orderInfo['user_id']])->first()->toArray();
        $user_spread_id = $userInfo['spread_id'];
        $now_price = 0;
        $now_level = 1;
        $level_ping = 1;

        $zunka_price = 0;
        $dong_price = 0;
        //执行业绩测试
        while(true){
            //没有上级直接走
            if($user_spread_id == 0){
                break;
            }




            $bili = [0,0.13,0.23,0.31,0.39,0.46];
            $userItemInfo = UsersDao::builder_query(['user_id'=>$user_spread_id])->first()->toArray();

            if($userItemInfo['vip_level'] < $now_level){
                $user_spread_id = $userItemInfo['spread_id'];
                continue;
            }

            //判断是初级董事
            if($userItemInfo['vip_dong_level'] > 0){
                $dong_lilv = 0.01;
                if($userItemInfo['vip_dong_level'] == 2){
                    $dong_lilv = 0.015;
                }else if($userItemInfo['vip_dong_level'] == 3){
                    $dong_lilv = 0.02;
                }
                $item_price = bcsub(bcmul($pv,$dong_lilv,2),$dong_price,2);
                $dong_price = $dong_price + $item_price;
                BillsDao::xiaoFeiUpdate($item_price,$user_spread_id,'董事分红');
            }


            //尊卡会员拿分红奖励
            if($userItemInfo['vip_level'] >= 5){
                $zunka_bili = 0.02;
                if($userItemInfo['pv_nums_tuan'] >= 130001 && $userItemInfo['pv_nums_tuan'] <= 390000){
                    $zunka_bili = 0.03;
                }else if($userItemInfo['pv_nums_tuan'] >= 390001 && $userItemInfo['pv_nums_tuan'] <= 810000){
                    $zunka_bili = 0.04;
                }else if($userItemInfo['pv_nums_tuan'] >= 810001 && $userItemInfo['pv_nums_tuan'] <= 1390000){
                    $zunka_bili = 0.05;
                }else if($userItemInfo['pv_nums_tuan'] >= 1390001 && $userItemInfo['pv_nums_tuan'] <= 1930000){
                    $zunka_bili = 0.06;
                }else if($userItemInfo['pv_nums_tuan'] >= 1930001 && $userItemInfo['pv_nums_tuan'] <= 2690000){
                    $zunka_bili = 0.07;
                }else if($userItemInfo['pv_nums_tuan'] >= 2690001 && $userItemInfo['pv_nums_tuan'] <= 3490000){
                    $zunka_bili = 0.08;
                }else if($userItemInfo['pv_nums_tuan'] >= 3490001 && $userItemInfo['pv_nums_tuan'] <= 4550000){
                    $zunka_bili = 0.09;
                }else if($userItemInfo['pv_nums_tuan'] >= 4550001){
                    $zunka_bili = 0.1;
                }
                //计算这个人的团队业绩
                $zunka_price_item = bcsub(bcmul($pv,$zunka_bili,2),$zunka_price,2);
                $zunka_price=$zunka_price + $zunka_price_item;
                if($zunka_price_item>0){
                    BillsDao::xiaoFeiUpdate($zunka_price_item,$user_spread_id,'高级分红');
                }
            }

            //平级奖励
            if($now_level >= 2){
                if($userItemInfo['vip_level'] == $now_level){
                    if($now_level == 2){
                        if($level_ping > 1){
                            continue;
                        }
                        BillsDao::xiaoFeiUpdate(bcmul(0.03,$pv,2),$user_spread_id,'下级购买商品获得奖励(平级奖励)');
                        $level_ping+=1;
                    }else if($now_level == 3){
                        if($level_ping > 2){
                            continue;
                        }
                        $lilvs = [0,0.03,0.005];
                        BillsDao::xiaoFeiUpdate(bcmul($lilvs[$level_ping],$pv,2),$user_spread_id,'下级购买商品获得奖励(平级奖励)');
                        $level_ping+=1;
                    }else if($now_level == 4){
                        if($level_ping > 3){
                            continue;
                        }
                        $lilvs = [0,0.03,0.005,0.005];
                        BillsDao::xiaoFeiUpdate(bcmul($lilvs[$level_ping],$pv,2),$user_spread_id,'下级购买商品获得奖励(平级奖励)');
                        $level_ping+=1;
                    }else if($now_level == 5){
                        if($level_ping > 3){
                            continue;
                        }
                        $lilvs = [0,0.03,0.005,0.005];
                        BillsDao::xiaoFeiUpdate(bcmul($lilvs[$level_ping],$pv,2),$user_spread_id,'下级购买商品获得奖励(平级奖励)');
                        $level_ping+=1;
                    }
                    $user_spread_id = $userItemInfo['spread_id'];

                    continue;
                }
            }





            $now_level = $userItemInfo['vip_level'];
            $level_ping = 1;
            //现在的总金额
            $itemLevelPrice = bcsub(bcmul($bili[$userItemInfo['vip_level']],$pv,2),$now_price,2);
            $now_price = bcadd($itemLevelPrice,$now_price,2);
            BillsDao::xiaoFeiUpdate($itemLevelPrice,$user_spread_id,'下级购买商品获得奖励');
            $user_spread_id = $userItemInfo['spread_id'];
        }
    }

    private static function changeLevel(array $orderInfo)
    {
        $goodsInfo = json_decode($orderInfo['orders_json_data'],true);
        $pv = $goodsInfo['pv'];

        if($pv == 0){
            return;
        }

        //给自己增加业绩
        UsersDao::builder_query(['user_id'=>$orderInfo['user_id']])->increment('pv_nums_ziji',$pv);
        //给团队增加业绩银卡会员才能享受业绩
        UsersDao::builder_query()->where('spread_ids','like','%,'.$orderInfo['user_id'].',%')
            ->where('vip_level','>=',1)
            ->increment('pv_nums_tuan',$pv);
        $userInfo = UsersDao::builder_query(['user_id'=>$orderInfo['user_id']])->first()->toArray();
        $level = $userInfo['vip_level'];
        if($level == 0){
            if($pv >= 998){
                $level = 1;
            }
        }
        if($level == 1){
            if($pv >= 4990){
                $level = 2;
            }
        }
        if($level == 2){
            if($pv >= 20958){
                $level = 3;
            }
        }
        UsersDao::builder_query(['user_id'=>$orderInfo['user_id']])->update([
            'vip_level'=>$level
        ]);
    }

    /**
     * @throws SysExceptions
     */
    private static function changeShopData(array $orderInfo)
    {
        $goodsInfo = json_decode($orderInfo['orders_json_data'],true);
        $pv = $goodsInfo['pv'];
        //没有PV不参加
        if($pv == 0){
            return;
        }
        if($goodsInfo['category_id'] != 5) {
            //查询店铺相关=>有人填写店铺号码
            if ($orderInfo['shop_nums'] != '') {
                $user_shop_dao = UsersDao::builder_query([
                    'shop_nums' => $orderInfo['shop_nums']
                ]);
                if (!$user_shop_dao->exists()) {
                    return;
                }
                $user_shop_info = $user_shop_dao->first()->toArray();
                //8%利润
                $money_price_decimal = bcmul($pv, 0.08, 2);
                BillsDao::xiaoFeiUpdate($money_price_decimal, $user_shop_info['user_id'], '用户购买产品店体店补');



                //区域奖励
                $city_str_shop = explode(',',$user_shop_info['city_str']);
                array_pop($city_str_shop);
                array_shift($city_str_shop);
                $user_xianqu_query = UsersDao::builder_query()
                    ->where('city_str','LIKE','%,'.$city_str_shop[2].',%')->where('shop_level',2);
                $user_shiqu_query = UsersDao::builder_query()
                    ->where('city_str','LIKE','%,'.$city_str_shop[1].',%')->where('shop_level',3);
                $user_sheng_query = UsersDao::builder_query()
                    ->where('city_str','LIKE','%,'.$city_str_shop[0].',%')->where('shop_level',4);
                $now_xianxia_price = 0;
                if($user_xianqu_query->exists()){
                    $user_xianqu_query = $user_xianqu_query->first()->toArray();
                    $bili = 0.06;
                    $price_item = bcsub(bcmul($bili,$pv,2),$now_xianxia_price,2);
                    if($price_item > 0){
                        BillsDao::xiaoFeiUpdate($price_item,$user_xianqu_query['user_id'],'店铺区域奖励(县区)');
                    }
                    $now_xianxia_price+=$price_item;
                }

                if($user_shiqu_query->exists()){
                    $user_shiqu_query = $user_shiqu_query->first()->toArray();
                    $bili = 0.10;
                    $price_item = bcsub(bcmul($bili,$pv,2),$now_xianxia_price,2);
                    if($price_item > 0){
                        BillsDao::xiaoFeiUpdate($price_item,$user_shiqu_query['user_id'],'店铺区域奖励(市区)');
                    }
                    $now_xianxia_price+=$price_item;

                }

                if($user_sheng_query->exists()){
                    $user_sheng_query = $user_sheng_query->first()->toArray();
                    $bili = 0.12;
                    $price_item = bcsub(bcmul($bili,$pv,2),$now_xianxia_price,2);
                    if($price_item > 0){
                        BillsDao::xiaoFeiUpdate($price_item,$user_sheng_query['user_id'],'店铺区域奖励(市区)');
                    }

                }
                //店铺铺店铺
                $index = 1;
                $user_spread_id = $user_shop_info['spread_id'];

                //查找上级店铺
                while (true) {
                    if ($index >= 3) {
                        break;
                    }
                    if ($user_spread_id == 0) {
                        break;
                    }
                    $user_spread_info = UsersDao::builder_query(['user_id' => $user_spread_id])->first()->toArray();

                    if ($user_spread_info['shop_level'] == 0) {
                        $user_spread_id = $user_spread_info['spread_id'];
                        continue;
                    }
                    $bili = [0, 0.06, 0.04, 0.04];
                    $price_item = bcmul($pv, $bili[$index], 2);
                    if ($price_item > 0) {
                        BillsDao::xiaoFeiUpdate($price_item, $user_spread_id, '店推店提成');
                    }

                    $user_spread_id = $user_spread_info['spread_id'];
                    $index++;
                }

            }
        }

        //根据收货地址给提成=>网体店补会员区专享

        if($goodsInfo['category_id'] == 5) {
            $json_data_address = json_decode($orderInfo['address_json'], true);

            $xiangzhen_id = $json_data_address['xiangzhen_id'];
            $area_id = $json_data_address['area_id'];
            $city_id = $json_data_address['city_id'];
            $now_shop_level_price = 0;
            $user_xiang_zhen = UsersDao::builder_query()->where('shop_level', 1)
                ->where('city_str', 'LIKE', '%,' . $xiangzhen_id . ',%');

            if ($user_xiang_zhen->exists()) {
                $user_xiang_zhen = $user_xiang_zhen->first()->toArray();
                $bili_xiang = 0.007;
                $price_item = bcmul($bili_xiang, $pv, 2);
                $now_shop_level_price += $price_item;
                BillsDao::xiaoFeiUpdate($price_item, $user_xiang_zhen['user_id'], '乡镇网体店补');
            }


            $user_area_zhen = UsersDao::builder_query()->where('shop_level', 2)
                ->where('city_str', 'LIKE', '%,' . $city_id . ',%');
            if ($user_area_zhen->exists()) {
                $user_area_zhen = $user_area_zhen->first()->toArray();
                $bili_xiang = 0.01;
                $price_item = bcsub(bcmul($bili_xiang, $pv, 2), $now_shop_level_price, 2);
                $now_shop_level_price += $price_item;
                BillsDao::xiaoFeiUpdate($price_item, $user_area_zhen['user_id'], '区域网体店补');
            }


            $user_city_zhen = UsersDao::builder_query()->where('shop_level', 3)
                ->where('city_str', 'LIKE', '%,' . $area_id . ',%');
            if ($user_city_zhen->exists()) {
                $user_city_zhen = $user_city_zhen->first()->toArray();
                $bili_xiang = 0.013;
                $price_item = bcsub(bcmul($bili_xiang, $pv, 2), $now_shop_level_price, 2);
                $now_shop_level_price += $price_item;
                BillsDao::xiaoFeiUpdate($price_item, $user_city_zhen['user_id'], '市区网体店补');
            }


            $user_province_zhen = UsersDao::builder_query()->where('shop_level', 4)
                ->where('city_str', 'LIKE', '%,' . $area_id . ',%');
            if ($user_province_zhen->exists()) {
                $user_province_zhen = $user_province_zhen->first()->toArray();
                $bili_xiang = 0.015;
                $price_item = bcsub(bcmul($bili_xiang, $pv, 2), $now_shop_level_price, 2);
                BillsDao::xiaoFeiUpdate($price_item, $user_province_zhen['user_id'], '省市网体店补');
            }
        }
    }


}
